package com.wwt.server.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwt.server.mapper.AdminMapper;
import com.wwt.server.pojo.Admin;
import com.wwt.server.properties.JwtProperties;
import com.wwt.server.service.IAdminService;
import com.wwt.server.service.IRoleService;
import com.wwt.server.utils.AdminUtils;
import com.wwt.server.utils.JWTUtils;
import com.wwt.server.vo.ErrorCode;
import com.wwt.server.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Tao
 * @since 2021-12-05
 */
@Service
//@PropertySource("classpath:application.yml")
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private UserDetailsService userDetailsService;
    //@Value("${token.tokenHeader}")
    private String tokenHead=new JwtProperties().getTokenHead();  //token放在前端哪个位置
    @Resource
    private AdminMapper adminMapper;
    @Autowired
    private IRoleService roleService;
    /**
     * 登录功能 实体类实现UserDetails接口
     * @param username
     * @param password
     * @return
     */
    @Override
    public Result login(String username, String password, String code, HttpServletRequest request) {
        //先检验验证码
        String  kaptcha = (String)request.getSession().getAttribute("kaptcha");
        if (kaptcha.isEmpty() || !code.equals(kaptcha))
            return Result.fail(ErrorCode.KAPTCHA_ERROR.getMessage(),ErrorCode.KAPTCHA_ERROR.getCode());
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails==null || !new BCryptPasswordEncoder().matches(password,userDetails.getPassword()))
            return Result.fail(ErrorCode.USERNAME_OR_PASSWORD_ERROR.getMessage(),ErrorCode.USERNAME_OR_PASSWORD_ERROR.getCode());
        if (userDetails.isEnabled()==false)
            return Result.fail(ErrorCode.ACCOUNT_DENY.getMessage(),ErrorCode.ACCOUNT_DENY.getCode());
        //验证通过 生成Token
        String token = JWTUtils.createTokenByUser(userDetails);
        //封装认证成功后的用户信息  ****
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        HashMap<String, Object> map = new HashMap();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return Result.success("登陆成功!",map);
    }

    /**
     * 获取当前用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminInfo(String  username) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username)
                .eq("enabled",true);
        Admin admin = adminMapper.selectOne(wrapper);
        //admin.setPassword(null);
        //获取权限(角色列表)
        admin.setRoles(roleService.getRolesByAdminId(admin.getId()));
        return admin;
    }

    /**
     * 获取操作员名单
     * @param keywords
     * @return
     */

    @Override
    public List<Admin> getAdmin(String keywords) {
//        if (keywords==null)
//        {
//            System.out.println("空空空空空空空空");
//        }
//        if (keywords=="")
//        {
//            System.out.println("空格空格空空空空空空");
//        }
        Integer currentId = AdminUtils.getCurrentAdmin().getId();
        return adminMapper.getAdmin(keywords,currentId);
    }

    @Override
    public boolean updateById1(Admin admin) {
        return adminMapper.updateById1(admin);
    }

}
